package storage

import (
	"context"
	"github.com/go-redis/redis/v8"
)

type RedisStorage struct {
	client *redis.Client
	ctx    context.Context
}

func NewRedisStorage(addr, password string, db int) *RedisStorage {
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       db,
	})

	ctx := context.Background()

	// 测试连接
	if _, err := client.Ping(ctx).Result(); err != nil {
		panic("Redis connection failed: " + err.Error())
	}

	return &RedisStorage{
		client: client,
		ctx:    ctx,
	}
}

func (s *RedisStorage) Save(longURL, shortCode string) error {
	// 保存 shortCode -> longURL
	if err := s.client.Set(s.ctx, "url:"+shortCode, longURL, 0).Err(); err != nil {
		return err
	}

	// 保存 longURL -> shortCode 用于去重
	return s.client.Set(s.ctx, "code:"+longURL, shortCode, 0).Err()
}

func (s *RedisStorage) Get(shortCode string) (string, error) {
	longURL, err := s.client.Get(s.ctx, "url:"+shortCode).Result()
	if err == redis.Nil {
		return "", ErrURLNotFound
	}
	return longURL, err
}

func (s *RedisStorage) Exists(longURL string) (string, bool) {
	shortCode, err := s.client.Get(s.ctx, "code:"+longURL).Result()
	if err == redis.Nil {
		return "", false
	}
	return shortCode, true
}